package com.yuanda.erp9.syn.helper;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.innovation.ic.b1b.framework.util.StringUtils;
import com.yuanda.erp9.syn.contant.ExeConstant;
import com.yuanda.erp9.syn.enums.CachePrefixEnum;
import com.yuanda.erp9.syn.exception.TargetServerException;
import com.yuanda.erp9.syn.execule.command.Command;
import com.yuanda.erp9.syn.poi.SelfSupportExcelData;
import com.yuanda.erp9.syn.util.CacheUtil;
import com.yuanda.erp9.syn.util.EasyExcelUtils;
import com.yuanda.erp9.syn.util.MathUtil;
import com.yuanda.erp9.syn.util.OKHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Consumer;

/**
 * @ClassName SelfSupportHelper
 * @Description 自营帮助类
 * @Date 2023/1/6
 * @Author myq
 */
@Slf4j
@Component
public class SelfSupportHelper {

    @Resource
    private RetryOperateLogHelper retryOperateLogHelper;



    private final String skey = "278882d39f3d5c9a3c66e46d0c694c4f";
    private final String url = "http://vpn3.t996.top:810//Api/JTPriceAPI/HKJTPriceAll";

    /**
     * @Description:
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2023/1/910:40
     */
    public JSONObject sendHttpAndGetData(Integer typeId, int page) {
        JSONObject jsonObject = null;
        Map<String, String> queryMap = new HashMap<>();
        queryMap.put("num", String.valueOf(page));
        queryMap.put("typeID", String.valueOf(typeId));
        queryMap.put("key", skey);
        try {
            String s = OKHttpUtil.doPost(url, null, null, null, null, JSON.toJSONString(queryMap));
            Object parse = JSON.parse(s);
            jsonObject = JSONObject.parseObject(parse.toString());
        } catch (Exception e) {
            e.printStackTrace();
            throw new TargetServerException("okHttp发送post请求失败：" + e);
        }
        return jsonObject;
    }


    /**
     * @Description: 获取阶梯价格
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2023/1/1013:39
     */
    public List<Map<String, String>> getLadderPrice(String warehouse, JSONObject row, int typeId) {
        // 获取美元对RMB费率
        CacheUtil.ObjectCache objectCache = CacheUtil.ObjectCache.objectInit(CachePrefixEnum.EXCHANGE_RATES.getKey());
        BigDecimal rate = (BigDecimal) objectCache.get(CachePrefixEnum.EXCHANGE_RATES.getKey());
        List<Map<String, String>> ladderPriceList = new ArrayList<>();
        String ladprice = row.getString("LADPRICE").trim();
        String[] split = ladprice.replaceAll("\\s*￥*", "").replaceAll("&nbsp;*", "*").split("</br>");
        if (split.length == 1) {
            Map<String, String> ladderPriceMap = new LinkedHashMap<>();
            ladderPriceMap.put("min", "1");
            ladderPriceMap.put("max", "0");
            ladderPriceMap.put("position", "1");
            ladderPriceMap.put("price", "0.0000");
            ladderPriceMap.put("currency", "1");
            ladderPriceMap.put("discount_rate", "0.0000");
            ladderPriceMap.put("discount_price", "0.0000");
            ladderPriceList.add(ladderPriceMap);
            return ladderPriceList;
        }
        for (int z = 0; z < split.length; z++) {
            Map<String, String> ladderPriceMap = new LinkedHashMap<>();
            String laddprice = null;
            String ladpriceSplit = split[z];
            String substringCount = ladpriceSplit.substring(0, ladpriceSplit.indexOf("*"));
            String substringPrice = ladpriceSplit.substring(ladpriceSplit.lastIndexOf("*") + 1);

            int count = Integer.parseInt(substringCount);
            double price = Double.parseDouble(substringPrice);
            if (price <= 0) {
                continue;
            }
            // 计算阶梯价格
            if (warehouse.startsWith("香港")) {
                laddprice = MathUtil.multiply(price,rate);
                ladderPriceMap.put("currency", "2");
            } else {
                double addTax = 1.13;
                //如果typeid是1的，价格是已经加过税的了。
                if (typeId == 1) {
                    addTax = 1;
                }
                //baseprice = 第一个价格*1.13
                laddprice = MathUtil.multiply(price,addTax);
                ladderPriceMap.put("currency", "1");
            }
            if (split.length - 1 == z) {
                ladderPriceMap.put("max", "0");
            } else {
                ladderPriceMap.put("max", split[z + 1].substring(0, split[z + 1].indexOf("*")));
            }
            ladderPriceMap.put("min", String.valueOf(count));
            ladderPriceMap.put("position", String.valueOf(z + 1));
            ladderPriceMap.put("price", laddprice);
            ladderPriceMap.put("discount_rate", "0.0000");
            ladderPriceMap.put("discount_price", "0.0000");
            ladderPriceList.add(ladderPriceMap);
        }
        return ladderPriceList;
    }


    /**
     * @param supplierId
     * @Description: 读取excel数据并放入map
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2023/1/1014:38
     */
    public Map<String, Map<String, String>> readExcelGetList(Integer supplierId) {
        try {
            Map<String, Map<String, String>> map = new LinkedHashMap<>();
            EasyExcelUtils.readExcelAsStream(new ClassPathResource(ExeConstant.SUNLOCAL_XLSX_PATH).getInputStream(), SelfSupportExcelData.class, new Consumer<SelfSupportExcelData>() {
                @Override
                public void accept(SelfSupportExcelData selfSupportExcelData) {
                    try {
                        Map<String, String> sunlord = new LinkedHashMap<>();
                        sunlord.put("类型", selfSupportExcelData.getType());
                        sunlord.put("规格型号", selfSupportExcelData.getSpecificationsModel());
                        String specificationsParam = selfSupportExcelData.getSpecificationsParam();
                        String[] array = specificationsParam.split(" ");
                        String size = array[0];//尺寸
                        String templeteValue = array[1];//感值/容值
                        String accuracy = array[2];//精度
                        String electric = array[3];//额定电流/耐压
                        sunlord.put("尺寸", size);
                        sunlord.put("感值/容值", templeteValue);
                        sunlord.put("精度", accuracy);
                        sunlord.put("额定电流/耐压", electric);
                        map.put(selfSupportExcelData.getSpecificationsModel(), sunlord);
                    } catch (Exception e) {
                        log.warn("解析sunload.xlsx异常：{}", e.getMessage());
                        retryOperateLogHelper.add(selfSupportExcelData.toString(), supplierId, e.getMessage());
                    }
                }
            });
            return map;
        } catch (Exception e) {
            log.error("读取SUNLOAD.xls异常： " + e);
            throw new TargetServerException("读取SUNLOAD.xls异常");
        }
    }




}
